package com.buddies.lottery.ui.agent.register;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;

import com.blankj.utilcode.util.EncryptUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.buddies.lottery.App;
import com.buddies.lottery.R;
import com.buddies.lottery.base.BaseActivity;
import com.buddies.lottery.common.ConfigManager;
import com.buddies.lottery.data.bean.User;
import com.buddies.lottery.ui.MainActivity;
import com.buddies.lottery.utils.AppExitUtils;
import com.r0adkll.slidr.Slidr;


public class AgentRegisterActivity extends BaseActivity<AgentRegisterContract.Presenter> implements View.OnClickListener, AgentRegisterContract.View {

    private static final int REQUEST_MOBILE_LOGIN = 1;

    private Spinner mSpinner;

    private Button mRegisterBTN;
    private EditText mPhoneET;
    private EditText mPwdET;
    private ImageView mClearPhoneIV;
    private ImageView mClearPwdIV;

    private SeekBar mSeekBar;
    private TextView tvRebate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().setBackgroundDrawableResource(R.color.transparent);
        Slidr.attach(this, App.getSlidrConfig());
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_agent_register;
    }

    @Override
    protected void initView() {
        setUp();

        mSpinner = findViewById(R.id.spinner);

        mRegisterBTN = (Button) findViewById(R.id.btn_register);
        mPhoneET = (EditText) findViewById(R.id.et_phone);
        mPwdET = (EditText) findViewById(R.id.et_pwd);
        mClearPhoneIV = (ImageView) findViewById(R.id.iv_clear);
        mClearPwdIV = (ImageView) findViewById(R.id.iv_clear_pwd);

        mSeekBar = findViewById(R.id.seekBar);
        tvRebate = findViewById(R.id.tv_rebate);

        mRegisterBTN.setOnClickListener(this);
        mClearPhoneIV.setOnClickListener(this);
        mClearPwdIV.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        mPresenter = new AgentRegisterPresenter(this);

        Intent intent = getIntent();
        if (intent != null) {
            mPhoneET.setText(intent.getStringExtra("phone"));
        }

        setTitle(getResources().getString(R.string.agent_register));

        String[] userTypes = getResources().getStringArray(R.array.user_type);
        ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, userTypes);
        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mSpinner.setAdapter(spinnerAdapter);

        mPhoneET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                mClearPhoneIV.setVisibility(editable.length() == 0 ? View.GONE : View.VISIBLE);
                setCommitBtnEnable();
            }
        });
        mPhoneET.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                mClearPhoneIV.setVisibility(mPhoneET.length() == 0 || !hasFocus ? View.GONE : View.VISIBLE);
            }
        });

        mPwdET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                mClearPwdIV.setVisibility(editable.length() == 0 ? View.GONE : View.VISIBLE);
                setCommitBtnEnable();
            }
        });
        mPwdET.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                mClearPwdIV.setVisibility(mPwdET.length() == 0 || !hasFocus ? View.GONE : View.VISIBLE);
            }
        });

        float rebate = ConfigManager.getInstance().getRebate();
        int max = (int) (rebate * 100);
        mSeekBar.setMax(max);
        mSeekBar.setProgress(max);
        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                tvRebate.setText(String.format("%s%%", (float) progress / 100));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        tvRebate.setText(String.format("%s%%", ConfigManager.getInstance().getRebate()));

        setCommitBtnEnable();
    }

    public void setCommitBtnEnable() {
        boolean enabled = mPhoneET.length() > 0 && mPwdET.length() > 0;
        mRegisterBTN.setEnabled(enabled);
        if (!enabled) {
            mRegisterBTN.setAlpha(0.5f);
        } else {
            mRegisterBTN.setAlpha(1.0f);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_register:
                if (checkPhone() && checkPwd()) {
                    requestRegister();
                }
                KeyboardUtils.hideSoftInput(getActivity());
                break;

            case R.id.iv_clear:
                mPhoneET.setText("");
                break;

            case R.id.iv_clear_pwd:
                mPwdET.setText("");
                break;

        }
    }

    private void requestRegister() {
        final int userType = mSpinner.getSelectedItemPosition();
        final String phone = getPhone();
        final String pwd = getPwd();
        mPresenter.postRegister(userType, phone, EncryptUtils.encryptMD5ToString(pwd), (float) mSeekBar.getProgress() / 100);
        showProgressDialog(R.string.register_processing);
    }

    @Override
    public void registerSuccess(User user) {
        hideProgressDialog();
        showToast(R.string.register_success);
    }

    private boolean checkPhone() {
        String phone = getPhone();

        boolean check = false;
        if (TextUtils.isEmpty(phone)) {
            showToast(getString(R.string.login_phone_number_require));
        } else if (phone.contains(" ")) {
            showToast(getString(R.string.login_phone_number_not_blank));
        } else if (phone.length() < 6 || phone.length() > 18) {
            showToast(getString(R.string.login_phone_number_length_not_right));
        } else {
            check = true;
        }

        return check;
    }

    public String getPhone() {
        return mPhoneET.getText().toString();
    }

    private boolean checkPwd() {
        String pwd = getPwd();

        boolean check = false;
        if (TextUtils.isEmpty(pwd)) {
            showToast(getString(R.string.register_password_require));
        } else if (pwd.length() < 6 || pwd.length() > 20) {
            showToast(getString(R.string.register_password_condition));
        } else {
            check = true;
        }

        return check;
    }

    public String getPwd() {
        return mPwdET.getText().toString();
    }

    @Override
    public void onBackPressed() {
        AppExitUtils.getInstance().onBackPressed(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_MOBILE_LOGIN && resultCode == RESULT_OK) {
            setResult(RESULT_OK);
            finish();
        }
    }

    public static void launch(Context context) {
        Intent intent = new Intent(context, AgentRegisterActivity.class);
        context.startActivity(intent);
    }

}
